<template>
	<div class="login-box">
		<div class="login-title">
			<h2>登 录 Logo</h2>
		</div>
		<a-form ref="formRef" :style="{ width: '320px' }" :model="loginModel" @submit="handleSubmit">
			<a-form-item
				field="username"
				label="用户名"
				:rules="[{ required: true, message: 'name is required' }]"
				validate-trigger="blur"
				hide-label
			>
				<a-input v-model="loginModel.username" placeholder="请输入用户名" />
			</a-form-item>
			<a-form-item
				field="password"
				label="密码"
				:rules="[{ required: true, message: 'name is required' }]"
				validate-trigger="blur"
				hide-label
			>
				<a-input-password
					v-model="loginModel.password"
					placeholder="请输入密码"
					:allow-clear="true"
					autocomplete="off"
				/>
			</a-form-item>
			<a-form-item field="remember" hide-label>
				<a-checkbox v-model="loginModel.remember"> 记住我？ </a-checkbox>
			</a-form-item>
			<a-form-item hide-label>
				<a-button type="primary" html-type="submit" :loading="loading" long>登 录</a-button>
			</a-form-item>
		</a-form>
	</div>
</template>
<script lang="ts" setup>
import { ref } from "vue";
import { useRouter } from "vue-router";
import { Message } from "@arco-design/web-vue";
import { ValidatedError } from "@arco-design/web-vue/es/form/interface";
import { useUserStore } from "@/store";
import { LoginData } from "@/api/system/user";
import useLoading from "@/hooks/loading";

const errorMessage = ref("");
const router = useRouter();
const userStore = useUserStore();
const { loading, setLoading } = useLoading();

const loginModel = ref({
	username: "admin",
	password: "123456",
	remember: false,
});

const handleSubmit = async ({
	values,
	errors,
}: {
	errors: Record<string, ValidatedError> | undefined;
	values: Record<string, any>;
}) => {
	if (loading.value) return;
	if (!errors) {
		setLoading(true);
		try {
			await userStore.login(values as LoginData);
			// 登录成功提示
			Message.success({
				content: "登录成功",
				duration: 2000,
				onClose: function () {
					const { redirect, ...othersQuery } = router.currentRoute.value.query;
					router.push({
						name: (redirect as string) || "Workplace",
						query: {
							...othersQuery,
						},
					});
				},
			});
		} catch (err) {
			errorMessage.value = (err as Error).message;
		} finally {
			setLoading(false);
		}
	}
};
</script>
<style lang="less">
.login-box {
	height: 100vh;
	display: flex;
	flex-direction: column;
	justify-content: center;
	align-items: center;
}
</style>
